package cn.webrx;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;

public class Work5 {
    public static Map<String,String> map;
    static{
        map = new HashMap<>();
        map.put("504b0304","zip/jar");
        map.put("ffd8ffe0","jpg/jpeg");
        map.put("89504e47","png");
        map.put("25504446","pdf");
        map.put("52617221","rar");
    }
    public static void main(String[] args) {
        System.out.println(getFileType(new File("c:/user.mp4")));

        //System.out.println(getFileHeaderStr("c:/abc.zip",4));
        //System.out.println(getFileHeaderStr("c:/Del3.zip",4));

        //File[] fs = new File("d:/download").listFiles();
        //for(File f : fs){
        //    if(f.isFile()){
        //        System.out.printf("%s:%s%n",f.getName(),getFileHeaderStr(f,4));
        //    }
        //}


    }

    public static String getFileType(File src){
        String tt = getFileHeaderStr(src,4);
        String ext = "未知";
        if(map.containsKey(tt)){
            ext = map.get(tt);
        }
        return ext;
    }


    public static String getFileHeaderStr(String src,int size) {
        return getFileHeaderStr(new File(src), size);
    }

    public static String getFileHeaderStr(String src) {
        return getFileHeaderStr(new File(src), 8);
    }

    public static String getFileHeaderStr(File src, int size) {
        StringBuilder sbu = new StringBuilder();
        try (var is = new FileInputStream(src)) {
            byte[] buf = new byte[size];
            is.read(buf);
            for (byte b : buf) {
                sbu.append(String.format("%02x", b));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return sbu.toString();
        }
    }
}
